package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?")  // 每分钟执行一次
    public void processOverdueOrders() {
        log.info("超时订单d查询");
        // 根据订单状态查询未付款 且 超时15分钟 的订单
        LocalDateTime overdueTime = LocalDateTime.now().minusMinutes(15);
        List<Orders> list = orderMapper.selectOrderByStatus(Orders.PENDING_PAYMENT, overdueTime);
        // 如果未付款超时 15 分钟就关闭订单
        if(list != null && list.size() > 0) {
            for (Orders ordersDB : list) {
                Orders orders = new Orders();
                orders.setId(ordersDB.getId());
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单超时，已取消");

                orderMapper.update(orders);
            }
        }
    }

    /**
     * 处理已经完成派送 但 状态还是派送中的订单
     */
    @Scheduled(cron = "0 0 0 * * ?")  // 每天执行一次
    private void processDeliveryCompleted() {
        LocalDateTime checkTime = LocalDateTime.now();
        // 查询在凌晨 00:00 之前的订单
        List<Orders> list = orderMapper.selectOrderByStatus(Orders.DELIVERY_IN_PROGRESS, checkTime);
        if(list != null && list.size() > 0) {
            for (Orders ordersDB : list) {
                Orders orders = new Orders();
                orders.setId(ordersDB.getId());
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());

                orderMapper.update(orders);
            }
        }
    }
}
